package array

import (
	"container/heap"
	"fmt"
)

func eatenApples(apples []int, days []int) int {
	pq := &IntHeap{}
	i, ans := 0, 0
	for i < len(apples) {
		// 丢掉过期的苹果
		for pq.Len() > 0 && (*pq)[0][0] <= i {
			heap.Pop(pq)
		}
		// 加入新的苹果
		if i < len(apples) && apples[i] > 0 {
			// i + days[i] 过期的日子
			heap.Push(pq, []int{i + days[i], apples[i]})
		}
		// 吃掉一个
		if pq.Len() > 0 {
			ans++
			(*pq)[0][1]-- //个数-1
			if (*pq)[0][1] == 0 {
				heap.Pop(pq)
			}
		}
		i++
	}

	for pq.Len() > 0 {
		fmt.Println(pq)
		for pq.Len() > 0 && (*pq)[0][0] <= i {
			heap.Pop(pq)
		}

		if pq.Len() == 0 {
			break
		}

		var num int
		if (*pq)[0][0]-i < (*pq)[0][1] {
			num = (*pq)[0][0]
		} else {
			num = (*pq)[0][1]
		}
		ans += num
		i += num
		heap.Pop(pq)
	}

	return ans
}

type IntHeap [][]int

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i][0] < h[j][0] }
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h *IntHeap) Pop() interface{} {
	old := *h
	n := len(old)
	x := old[n-1]
	*h = old[0 : n-1]
	return x
}
func (h *IntHeap) Push(x interface{}) {
	*h = append(*h, x.([]int))
}
